package net.game.server.io.net.codec;

import net.game.server.game.player.Player;
import net.game.server.io.PlayerWorker;
import net.game.server.util.crypto.BASE64;
import net.game.server.util.crypto.IsaacRandom;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

import java.security.SecureRandom;

public class LoginDecoder extends FrameDecoder {
    @Override
    protected Object decode(ChannelHandlerContext channelHandlerContext, Channel channel, ChannelBuffer in) throws Exception {
        if(in.readableBytes() >= 1) {
            int loginOpcode = in.readByte();
            switch (loginOpcode) {
                case 0:
                    if(in.readableBytes() >= 1) {
                        int loginSize = in.readInt();
                        if(in.readableBytes() >= loginSize) {
                            long first = new SecureRandom(BASE64.encode("first").getBytes()).nextLong();
                            long second = new SecureRandom(BASE64.encode("second").getBytes()).nextLong();
                            int[] seed = {(int) (first >> 56), (int) (first >> 24), (int) first, (int) (second >> 48), (int) (second >> 16), (int) second};
                            IsaacRandom decipher = new IsaacRandom(seed);
                            for(int i = 0; i < seed.length; i++) {
                                seed[i] += 0x20;
                            }
                            IsaacRandom encipher = new IsaacRandom(seed);
                            String username = getString(in);
                            String password = BASE64.decode(getString(in));
                            Player player = PlayerWorker.load(username, password, channel);

                        }
                    }
                    break;
            }
        }
        return null;
    }
    
    private String getString(ChannelBuffer in) {
        StringBuilder bldr = new StringBuilder();
        byte b;
        while ((b = in.readByte()) != 0) {
            bldr.append((char) b);
        }
        return bldr.toString();
    }
}
